package com.shine.level.easy;

/**
 * 合并两个有序链表
 * @author zhangshao
 * @date 2021/7/1 10:21 上午
 */
public class MergeTwoListTest {
    /**
     * 合并两个有序链表
     * @param node1 有序链表1
     * @param node2 有序链表2
     * @return
     */
    public static ListNode mergeTwoList(ListNode node1,ListNode node2){
        ListNode result = new ListNode(-1);
        ListNode pre = result;
        // eg node1  1-->3-->5
        //    node2  2-->4-->6
        while(node1!=null && node2 !=null){
            if(node1.val <= node2.val){
                pre.next = node1;
                node1 = node1.next;
            }else{
                pre.next = node2;
                node2 = node2.next;
            }
            //移动pre指针
            pre = pre.next;
        }
        if(node1 !=null){
            pre.next = node1;
        }
        if(node2 !=null){
            pre.next = node2;
        }
        return result.next;
    }

    public static void print(ListNode headNode){
        //定义一个临时节点,用以辅助单链表便利操作
        ListNode tmpNode = headNode;
        StringBuilder sb = new StringBuilder();
        //定义循环，移动tmpNode
        while (tmpNode!=null){
            if(tmpNode.next !=null){
                sb.append(tmpNode.val +"->");
            }else {
                sb.append(tmpNode.val);
            }
            tmpNode = tmpNode.next;

        }
        System.out.println(sb.toString());
    }

    public static void main(String[] args) {
        ListNode node1_5 = new ListNode(5);
        ListNode node1_3 = new ListNode(3,node1_5);
        ListNode node1_1 = new ListNode(1,node1_3);


        ListNode node2_6 = new ListNode(6);
        ListNode node2_4 = new ListNode(4,node2_6);
        ListNode node2_2 = new ListNode(2,node2_4);

        ListNode result = mergeTwoList(node1_1, node2_2);
        print(result);

    }
}
